<template>
  <div style="display: flex; align-items: center; border-radius: 8px;
          background: white; margin: 7px; height: 50px">
    <van-icon name="enlarge" size="1.5rem" class="ml-2"/>
    <van-field :readonly="readonly"
        ref="mySearch"
        v-model="value"
        :placeholder="placeholder"
        :clearable="clearable"
        center
        @keydown.enter="keydownEnter"
        @blur="blur"
        style="padding: 0 0 0 10px; width: 85vw; background: none"
        :rules="[{ required: true }]"
    />
    <van-icon @click="rescan" v-if="rescanable && readonly" name="edit" size="1.5rem" class="mr-2 pl-2"/>
  </div>
</template>

<script setup lang="ts">
import { nextTick } from "vue";

const props = defineProps({
  placeholder: String,
  isFocus: Boolean,
  isReset: Boolean,
  clearable: Boolean,
  readonly: Boolean,
  rescanable: Boolean,
})

const { placeholder, isFocus, isReset } = toRefs(props)
const mySearch = ref(null);

onMounted(() => {
  if (isFocus.value) setFocus()
});

const value = ref('')
const readonly = ref(props.readonly)

const emits = defineEmits(['keydownEnter', 'rescan', 'searchChange', 'blur'])
const keydownEnter = () => {
  if ([undefined, null, ''].includes(value.value)) return
  emits('keydownEnter', value.value)
  if (isReset.value) {
    value.value = undefined
  }
}

const rescan = () => {
  readonly.value = false
  value.value = undefined;
  emits('rescan')
  nextTick(() => {
    setFocus()
  })
}

const setDisable = () => {
  readonly.value = true
}

const reset = () => {
  value.value = undefined;
}

const setFocus = () => {
  if (mySearch.value) {
    mySearch.value.focus();
  }
}

const setBlur = () => {
  if (mySearch.value) {
    mySearch.value.blur();
  }
}

const setValue = (value1) => {
  value.value = value1
}
const blur = () => {
  emits('blur', value.value)
}

defineExpose({
  reset,
  setDisable,
  setFocus,
  setBlur,
  setValue,
  blur
})
</script>

<style lang="less" scoped>
:deep(.van-field__body) {
  font-size: 0.8rem;
}
</style>
